package com.chungkui.demo.mvc;

import com.chungkui.check.core.BaseChungkuiCheckConfiguration;

import com.chungkui.check.handler.ratelimiter.impl.AbstractRedisRateLimiterServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.ReturnType;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;

/**
 * @Author: jason
 * @Date: 2020/1/14 12:54
 * @Version 1.0
 */

@Configuration
public class CheckConfiguration extends BaseChungkuiCheckConfiguration {

    @Bean
    public AbstractRedisRateLimiterServiceImpl redisRateLimiterService() {
        return new AbstractRedisRateLimiterServiceImpl() {
            @Autowired
            private RedisTemplate redisTemplate;
            @Override
            public List<Long> eval(String redisScript, int keySize, final String... argsL) {
                return (List<Long>) redisTemplate.execute((RedisConnection connection) -> connection.eval(redisScript.getBytes(),
                        ReturnType.fromJavaType(List.class),
                        keySize,
                        argsL[0].getBytes(),
                        argsL[1].getBytes(),
                        argsL[2].getBytes(),
                        argsL[3].getBytes(),
                        argsL[4].getBytes(),
                        argsL[5].getBytes()));

            }

            @Override
            public List<Long> evalSha(String redisSha, int keySize, String... scriptArgs) {
                return (List<Long>) redisTemplate.execute((RedisConnection connection) -> connection.evalSha(redisSha.getBytes(),
                        ReturnType.fromJavaType(List.class),
                        keySize,
                        scriptArgs[0].getBytes(),
                        scriptArgs[1].getBytes(),
                        scriptArgs[2].getBytes(),
                        scriptArgs[3].getBytes(),
                        scriptArgs[4].getBytes(),
                        scriptArgs[5].getBytes()));

            }
        };
    }


}
